package com.property.business.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.property.business.common.Result;
import com.property.business.entity.Information;
import com.property.business.service.IInformationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务-资讯（公告） 前端控制器
 * </p>
 *
 * @author 刘煦煌
 * @since 2023-11-24
 */
@Slf4j
@RestController
@RequestMapping("/information")
public class InformationController {

    @Resource
    private IInformationService informationService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Information information) {
        informationService.saveOrUpdate(information);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        informationService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        informationService.removeByIds(ids);
        return Result.success();
    }

    /**
     * 根据type查询数据
     * @param type
     * @return
     */
    @GetMapping("/list/{type}")
    public Result findAll(@PathVariable(value = "type", required = true) Integer type) {
        log.info("type:{}", type);
        type = Optional.of(type).orElse(1);
        LambdaQueryWrapper<Information> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Information::getType, type).orderByDesc(Information::getCreateTime);
        return Result.success(informationService.list(wrapper));
    }

    /**
     * 获取物业公告
     *
     * @return
     */
    @GetMapping("/list/title")
    public Result getPropertyNoticeTitle() {
        LambdaQueryWrapper<Information> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Information::getType, 1).orderByDesc(Information::getCreateTime).last("limit 3");
        List<Information> list = informationService.list(wrapper);
        List<String> collect = list.stream().map(Information::getName).collect(Collectors.toList());
        return Result.success(collect);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(informationService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Information> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Information::getCreateTime);
        return Result.success(informationService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

